package com.xyz.util;

import cn.hutool.core.util.ReflectUtil;
import org.springframework.lang.Nullable;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tongqiang
 * @description
 * @date 2022年07月19日
 */
public class ConvertVoUtil {
    // 将分散字段值放入集合中
    public static Map<String, List<Object>> convert(@Nullable Object source) {
        if (source == null) {
            return Collections.emptyMap();
        }
        Field[] fields = ReflectUtil.getFields(source.getClass());
        return Arrays.stream(fields).filter(field -> field.isAnnotationPresent(Item.class))
                .filter(field -> !Objects.isNull(ReflectUtil.getFieldValue(source, field)) && !ReflectUtil.getFieldValue(source, field).toString().equals(""))
                .collect(Collectors.groupingBy(field -> field.getAnnotation(Item.class).listOf(),
                        Collectors.mapping(field -> (ReflectUtil.getFieldValue(source, field)),
                                Collectors.toList())));
    }

    /**
     * 把单个对象中的String类型的null字段，转换为空字符串
     * 注意：只能转换String类型的字段
     *
     * @param <T> 待转化对象类型
     * @param cls 待转化对象
     * @return 转化好的对象
     */
    public static <T> T nullToString(T cls) {
        Field[] fields = cls.getClass().getDeclaredFields();
        if (fields.length == 0) {
            return cls;
        }
        for (Field field : fields) {
            if ("String".equals(field.getType().getSimpleName())) {
                field.setAccessible(true);
                try {
                    Object value = field.get(cls);
                    if (!field.isAnnotationPresent(Item.class) && (value == null || value.toString().equals(""))) {
                        field.set(cls, " ");
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return cls;
    }

    public static <T> T nullToStringBean(T cls) {
        Field[] fields = cls.getClass().getDeclaredFields();
        if (fields.length == 0) {
            return cls;
        }
        for (Field field : fields) {
            if ("String".equals(field.getType().getSimpleName())) {
                field.setAccessible(true);
                try {
                    Object value = field.get(cls);
                    if (value == null || value.toString().equals("")) {
                        field.set(cls, " ");
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return cls;
    }

}
